<template>
  <div class="v-slot-checkbox g-pd-l-8">
    <el-checkbox
      v-model="checked"
      :label="label"
      size="small"
      :indeterminate="indeterminate"
      :disabled="readonly || isModelDisabled"
      @change="handleChange as any"
    ></el-checkbox>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted, inject, Ref } from "vue";
import { propertyUtil } from "../../PropertyUtil";
import { CreateSpecification, InstanceSlotData, SlotValue } from "../../types";
import { SlotEditKey } from "@/constants/constants";
import { UpdateSlotValueDto } from "@/modules/model/service/dto";
import { modelService } from "@/modules/model/service";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

const map = new Map([
  [true, "是"],
  [false, "否"],
  [null, "空"]
]);

const props = defineProps<{
  instanceId: string | undefined;
  projectId: string;
  slotData: InstanceSlotData;
  slotValue: SlotValue | undefined | null;
  slotKey: SlotEditKey;
  readonly?: boolean;
  isMultiplicity?: boolean;
  nullable?: boolean;
}>();

const checked = ref<boolean>(props.slotValue?.value as boolean);

const label = computed(() => {
  return map.get(checked.value) || "空";
});
const indeterminate = computed(() => {
  return props.slotValue?.value === null;
});

watch(
  () => props.slotValue?.value,
  () => {
    checked.value = props.slotValue?.value as boolean;
  }
);

async function handleChange(value: boolean) {
  const slotData = props.slotData;

  if (props.slotKey === SlotEditKey.SlotValue) {
    const dto: CreateSpecification = {
      projectId: props.projectId,
      propertyId: slotData.propertyId,
      slotId: slotData.slotId,
      parentId: props.instanceId!,
      value: value,
      valueSpecificationId: props.slotValue?.id,
      key: props.slotKey
    };
    await propertyUtil.updatePropertySlotAndFresh(dto);
  } else if (props.slotKey === SlotEditKey.TagValue) {
    const slotValue = slotData.values.find(item => item.id === props.slotValue?.id);
    if (slotValue) {
      slotValue.value = value;
    }
    const values = slotData.values.map(item => item.value);

    const dto: UpdateSlotValueDto = {
      projectId: props.projectId,
      dataType: slotData.dataType,
      instanceId: props.instanceId!,
      isMultiplicity: slotData.isMultiplicity!,
      key: slotData.propertyId,
      updateMethod: "",
      value: values
    };
    await modelService.updateSlotValue(dto);
  }
}
onMounted(async () => {
  // await handleChange(false);
});
</script>
